package com.sita.test;


import java.util.Properties;

import org.eclipse.paho.client.mqttv3.*;

/**
 *
 * @author LP by 2014-04-24
 *
 */
public class MqttTestClient implements MqttCallback {

    private static final String MQTT_HOST = "ssl://127.0.0.1:6200";
    private static final String MQTT_CLIENT = "Test_";
    public static String caFilePath = "D:/for-iot/LURA/src/mytest/samplecerts/ca.crt";
    public static String clientCrtFilePath = "D:/for-iot/LURA/src/mytest/samplecerts/client.crt";
    public static String clientKeyFilePath = "D:/for-iot/LURA/src/mytest/samplecerts/client.key";

    public static MqttTestClient mqttServiceClient = null;

    private MqttClient client = null;
    private MqttConnectOptions options = null;

    /**
     * 单例模式构造类
     */
    public static MqttTestClient getInstance() {
        if (mqttServiceClient == null) {
            mqttServiceClient = new MqttTestClient();
        }
        return mqttServiceClient;
    }

    private MqttTestClient() {
        System.out.println("init MQTTClientService");
        init();
    }
    // The major API implementation follows :-

    /**
     * 初始化
     */
    private void init() {
        try {

            // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            //client = new MqttClient(MQTT_HOST, MQTT_CLIENT, new MemoryPersistence());
            client=new MqttClient(MQTT_HOST, MQTT_CLIENT);
            // MQTT的连接设置
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName("ypf");
            // 设置连接的密码
            options.setPassword("ruijie".toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(50);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(30);
            // TLS连接配置
           // options.setSocketFactory(
           //         SslUtil.getSocketFactory(caFilePath, clientCrtFilePath, clientKeyFilePath, "cs123456"));

            // 设置回调
            client.setCallback(this);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 连接到MQTT
     */
    void connect() {
        System.out.println("Start connect----------");
        try {
            client.connect(options);
            //订阅主题的方法，2为消息的质量
            client.subscribe("+/#", 0);
            client.subscribe("sub/oo");
            //发送消息
            publish("test", "撒打发水电费水电费");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开连接到MQTT
     */
    public void disconnect() {
        System.out.println("Start disconnect----------");
        try {
            client.disconnect();
        } catch (MqttSecurityException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布消息
     * @param topic 主题
     * @param msg 消息
     */
    public void publish(String topic, String msg) {
        System.out.println("Start publish----------");
        try {
            MqttTopic mqttTopic = client.getTopic(topic);
            //2为消息的质量
            MqttDeliveryToken messageToken = mqttTopic.publish(msg.getBytes(), 2, true);
            System.out.println("publish success==>"+messageToken.getMessage());
            //            client.publish(topic, 2, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // -------------------------------------------------回调方法------------------------------------------------------------//

    /**
     * 连接断开触发此方法
     */
    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("Connection Lost---------->" + cause.getMessage());
    }

    /**
     * 消息达到触发此方法
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        System.out.println("top" + ":" + s.toString());
    }



    /**
     * 消息发送成功触发此方法
     */

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        try {
            System.out.println("deliveryComplete---------" + iMqttDeliveryToken.getMessage());
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }




    public static void main(String[] args)throws Exception {

        //MqttServiceClient.getInstance().disconnect();
        MqttTestClient.getInstance().connect();

        new Thread() {
            public void run() {
                int count = 0;
                while(true && count < 1) {
                    try {
                        Thread.sleep(1000*3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MqttTestClient.getInstance().publish("test1/ypf", "hello world ! count=" + count);
                    count ++;
                }
            };
        }.start();
    }

}